package com.cuanbobox.controller;

import android.os.Environment;
import android.text.TextUtils;

import com.cuanbobox.base.App;
import com.cuanbobox.bean.ConfigInfo;
import com.cuanbobox.bean.ScanDevBean;
import com.cuanbobox.constant.CbConstant;
import com.cuanbobox.utils.ADBUtil;
import com.cuanbobox.utils.BroadcastUtil;
import com.cuanbobox.utils.FileUtil;
import com.cuanbobox.utils.HtmlUtil;
import com.cuanbobox.utils.HttpFileDownload;
import com.cuanbobox.utils.IpUtil;
import com.cuanbobox.utils.LogUtil;
import com.cuanbobox.utils.SharedPreferencesUtil;
import com.cuanbobox.utils.TcpUtil;
import com.cuanbobox.utils.UserMD5Util;
import com.google.gson.Gson;
import com.yanzhenjie.andserver.annotation.Controller;
import com.yanzhenjie.andserver.annotation.GetMapping;
import com.yanzhenjie.andserver.annotation.PostMapping;
import com.yanzhenjie.andserver.annotation.RequestParam;
import com.yanzhenjie.andserver.annotation.ResponseBody;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.http.cookie.Cookie;
import com.yanzhenjie.andserver.http.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Controller
public class CBController {

    @GetMapping("/")
    public String index(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            //动态生成index文件
            HtmlUtil.generateIndex();
            return "forward:/index.html";
        } else {
            HtmlUtil.generateLogin(request);
            return "forward:/login.html";
        }
    }

    @GetMapping("/systemRestart")
    String systemRestart(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            ADBUtil.reboot();
            return "forward:/index.html";
        } else {
            return "请先登陆！";
        }
    }

    /**
     *检查版本
     */
    @GetMapping("/checkVersion")
    public String checkVersion(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            //动态生成sceneLinkage文件
            HtmlUtil.generateCheckVersion();
            return "forward:/checkVersion.html";
        } else {
            HtmlUtil.generateLogin(request);
            return "forward:/login.html";
        }
    }

    /**
     *登陆页
     */
    @PostMapping("/login")
    String login(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        String password = request.getParameter("password");
        HtmlUtil.generateLogin(request);
        if (App.configInfo.getPwd().equals(password)) {
            Cookie cookie = new Cookie("user", UserMD5Util.getMD5());
            response.addCookie(cookie);
            return "redirect:/";
        }else{
            return "redirect:/?loginResult=-1";
        }
    }

    /**
     *获取教室配置信息
     */
    @GetMapping("/getConfigInfoFileName")
    @ResponseBody
    String getConfigInfoFileName(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        response.setStatus(200);
        return App.configInfo.getClassName() + "_教室配置信息";
    }

    /**
     *日志页
     */
    @GetMapping("/log")
    public String log(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            //动态生成index文件
            HtmlUtil.generateLog();
            return "forward:/log.html";
        } else {
            return "forward:/login.html";
        }
    }

    @GetMapping("/share")
    public String share(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        HtmlUtil.generateShare();
        return "forward:/share.html";
    }

    @GetMapping("/updateApp")
    @ResponseBody
    public String updateApp(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        String apkPath = request.getParameter("apkPath");
        if(apkPath.contains(IpUtil.getIpAddressString())) {
            return "升级的IP不能是自己!";
        }else {
            new HttpFileDownload(apkPath, null).start();
            return "ok";
        }

    }

    /**
     *保存参数设置
     */
    @PostMapping("/set")
    String set(HttpRequest request) {
        if (HtmlUtil.loginVerify(request)) {
            String className = request.getParameter("className");
            if(!TextUtils.isEmpty(className)){
                App.configInfo.setClassName(className);
            }

            String classId = request.getParameter("classId");
            if(!TextUtils.isEmpty(classId)) {
                App.configInfo.setClassId(classId);
            }
            String pwd = request.getParameter("pwd");
            if(!TextUtils.isEmpty(pwd)) {
                App.configInfo.setPwd(pwd);
            }
            String matrix = request.getParameter("matrix");
            App.configInfo.setMatrixIP(matrix);
            String pcIP = request.getParameter("pcIP");
            App.configInfo.setPcIP(pcIP);
            String matrixPort = request.getParameter("matrixPort");
            int imatrixPort=1001;
            try{
                imatrixPort=Integer.valueOf(matrixPort);
            } catch (Exception e){}
            App.configInfo.setMatrixPort(imatrixPort);
            SharedPreferencesUtil.saveBean(App.getInstance(),App.configInfo);
            return "redirect:/";
        } else {
            return "forward:/login.html";
        }
    }

    /**
     *更新教室信息
     */
    @PostMapping("/upload")
    String upload(@RequestParam("appconfig") MultipartFile appConfig, HttpRequest request) throws IOException {
        if (HtmlUtil.loginVerify(request)) {
            /*File localFile = new File(App.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()+"/appConfig.txt");
        appConfig.transferTo(localFile);*/
            try {
                String strData = new String(appConfig.getBytes(), "gbk");
                App.configInfo = new Gson().fromJson(strData, ConfigInfo.class);
                SharedPreferencesUtil.saveBean(App.getInstance(), App.configInfo);
                //BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_RESTART_EQUIPMENTCONTROLACTIVITY);
                LogUtil.add("文本内容", "" + strData, "web更新教室信息");
            }catch (Exception e){}
            return "redirect:/";
        } else {
            return "forward:/login.html";
        }
    }

    /**
     *更新apk
     */
    @PostMapping("/inputApk")
    String inputApk(@RequestParam("apkFile") MultipartFile apkFile, HttpRequest request, HttpResponse response) throws IOException {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            try{
                String dir = App.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/apk/";
                boolean bl = FileUtil.deleteAllFile(new File(dir));
                new File(dir).mkdirs();
                LogUtil.add("操作", "删除apk目录下的所有文件=" + bl, "ApkUtil");
                String path = dir + apkFile.getFilename();
                LogUtil.add("保存地址", path, "ApkUtil");
                FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
                fileOutputStream.write(apkFile.getBytes());
                fileOutputStream.flush();
                fileOutputStream.close();
                LogUtil.add("操作结果", "安装包保存成功", "ApkUtil");
                BroadcastUtil.sendBroadcast(CbConstant.TYPE_INSTALL_APK,path);
            }catch (Exception e){}
            return "redirect:/";
        } else {
            return "forward:/login.html";
        }
    }

    /**
     *下载教室信息
     */
    @GetMapping("/classRoomDownload")
    public String classRoomDownload(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            File fDir = new File(App.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/classRoomInfo");
            String savePath = fDir.getAbsolutePath() + "/" + App.configInfo.getClassName() + "_教室配置信息.txt";
            FileUtil.writeDataToFile(App.getInstance(), new Gson().toJson(App.configInfo), savePath, new FileUtil.ResultListener() {
                @Override
                public void fail(final String msg) {

                }

                @Override
                public void success() {

                }
            });
            return "forward:/classRoomInfo";
        } else {
            return "forward:/login.html";
        }
    }

    /**
     *清空日志
     */
    @GetMapping("/clearLog")
    public String clearLog(HttpRequest request, HttpResponse response) {
        response.addHeader("Access-Control-Allow-Origin","*");
        if (HtmlUtil.loginVerify(request)) {
            LogUtil.clearAllLog();
            return "forward:/index.html";
        } else {
            return "forward:/login.html";
        }
    }

    @GetMapping("/heartbeat")
    @ResponseBody
    public String heartbeat(HttpRequest request, HttpResponse response) {
        return "ok";
    }
}
